//
//  LoginViewController.m
//  YunGou
//
//  Created by macbook on 16/5/18.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "LoginViewController.h"
#import "NSString+Regexp.h"
#import "UIBarButtonItem+Extension.h"
#import "UMSocial.h"
#import <UIImage+AFNetworking.h>
#import "RegisterViewController.h"
#import "ForgetPwdViewController.h"

@interface LoginViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneText;
@property (weak, nonatomic) IBOutlet UITextField *passwordText;
@property (nonatomic,strong) NSArray *thirdLoginArray;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint1;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint3;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [_phoneText setValue:[UIColor colorWithHexString:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    [_passwordText setValue:[UIColor colorWithHexString:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    
    _heightConstraint.constant = 62 * ScreenHeight / 667;
    _heightConstraint1.constant = 56 * ScreenHeight / 667;
    _heightConstraint3.constant = 50 * ScreenHeight / 667;
    
    _thirdLoginArray = @[UMShareToWechatSession,UMShareToQQ];
    
    if (_isPresent) {
        [self setupBackBar];
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    [self.view addGestureRecognizer:tap];
}

- (void)hideKeyBoard{
    [self.view endEditing:YES];
}

//注：三方登录成功后 若服务器中不存在三方登录的用户信息，则将用户信息登录服务器。反之，不再将用户信息返回到服务器
- (IBAction)thirdLoginClicked:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:_thirdLoginArray[btn.tag - 1]];
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            [UserDefaults setBool:YES forKey:@"is_login"];
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:snsPlatform.platformName];
            NSString *usid = snsAccount.usid;
            NSString *thirdImage = snsAccount.iconURL;
            NSString *thirdName = snsAccount.userName;
            [NetWorkTool thirdLoginWithThirdPartyUid:usid success:^(id object) {
                if ([object[@"code"] integerValue] == 1) {
                    UserModel *model  = [UserModel sharedInstance];
                    [model clear];
                    UserModel *temp = [UserModel mj_objectWithKeyValues:object[@"data"][@"register_info"]];
                    [model mj_setKeyValues:[temp mj_keyValues]];
                    [UserDefaults setBool:YES forKey:@"ThirdLogin"];
                    [UserDefaults setObject:usid forKey:@"uid"];
                    
                    if ([model.username isEqualToString:@""] || [model.img isEqualToString:@""]) {
                        [NetWorkTool uploadWithImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:thirdImage]]] success:^(id object) {
                            if ([object[@"code"] integerValue] == 1) {
                                NSMutableString *path = object[@"path"];
                                NSString *subPath = [path substringFromIndex:18];
                                [NetWorkTool updateUserInfoWithNickName:thirdName img:subPath gender:nil birth:nil qq:nil email:nil address:nil success:^(id object) {
                                    if ([object[@"code"] integerValue] == 1) {
                                        [[UserModel sharedInstance] setValue:subPath forKey:@"img"];
                                        [[UserModel sharedInstance] setValue:thirdName forKey:@"username"];
                                        [UserDefaults setBool:YES forKey:@"is_login"];
                                        
                                        if (_isPresent) {
                                            [self dismissViewControllerAnimated:YES completion:nil];
                                            return;
                                        }
                                        self.tabBarController.selectedIndex = 0;
                                        [self.navigationController popToRootViewControllerAnimated:YES];
                                    }else{
                                        [MBProgressHUD showError:@"登录失败"];
                                    }
                                } failure:^(NSError *error) {
                                    FZLog(@"%@",error);
                                }];
                            }
                        } failure:^(NSError *error) {
                            
                        }];
                    }else{
                        if (_isPresent) {
                            [self dismissViewControllerAnimated:YES completion:nil];
                            return;
                        }
                        self.tabBarController.selectedIndex = 0;
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }
                    
                }
            } failure:^(NSError *error) {
                
            }];
            
        }else{
            NSLog(@"error");
        }
    });
}


- (void)setupBackBar{
    UIBarButtonItem *backItem = [UIBarButtonItem barButtonTitle:nil image:@"shouye_zuo" frame:CGRectMake(0, 0, 8, 15) target:self sel:@selector(back)];
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)loginClicked:(id)sender {
    NSString *phone = _phoneText.text;
    NSString *password = _passwordText.text;
    if (phone.length != 0) {
        if ([NSString isMobileNumber:phone]) {
            if (password.length != 0) {
                [MBProgressHUD showMessage:@"正在登录"];
                [NetWorkTool loginWithPhone:phone password:password success:^(id object) {
                    [MBProgressHUD hideHUD];
                    if ([object[@"code"] integerValue] == 1) {
                        [UserDefaults setObject:phone forKey:@"phone"];
                        [UserDefaults setObject:password forKey:@"password"];
                        [UserDefaults setBool:YES forKey:@"is_login"];
                        
                        UserModel *model  = [UserModel sharedInstance];
                        [model clear];
                        UserModel *temp = [UserModel mj_objectWithKeyValues:object[@"data"][@"register_info"]];
                        [model mj_setKeyValues:[temp mj_keyValues]];
                        [UserDefaults setBool:NO forKey:@"ThirdLogin"];
                        [UserDefaults setObject:model.uid forKey:@"uid"];
                        
                        if (_isPresent) {
                            [self dismissViewControllerAnimated:YES completion:nil];
                            return;
                        }
                        self.tabBarController.selectedIndex = 0;
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }else{
                        [MBProgressHUD showError:@"登录失败"];
                    }
                } failure:^(NSError *error) {
                    
                }];
            }else{
                [MBProgressHUD showError:@"密码不能为空"];
            }
        }else{
            [MBProgressHUD showError:@"号码格式不正确"];
        }
    }else{
        [MBProgressHUD showError:@"号码不能为空"];
    }
}
- (IBAction)registerClicked:(id)sender {
    RegisterViewController *reigsterVC = SB(@"Login", @"RegisterVC");
    [self.navigationController pushViewController:reigsterVC animated:YES];
}

- (IBAction)forgetPassword:(id)sender {
    ForgetPwdViewController *forgetPwdVC = SB(@"Login", @"ForgetPwdVC");
    [self.navigationController pushViewController:forgetPwdVC animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if ([textField returnKeyType] != UIReturnKeyDone) {
        NSInteger nextTag = textField.tag + 1;
        UITextField *nextTextField = [self.view viewWithTag:nextTag];
        [nextTextField becomeFirstResponder];
    }else{
        [textField resignFirstResponder];
    }
    return YES;
}


- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    _isPresent = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
